﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using Microsoft.Xna.Framework.Graphics;
using AAEngine.Engine.Entities;
using AAEngine.Rendering2D.SpriteSheet;

namespace AAEngine.Rendering2D.Renderers
{
    public class SpriteSheetRenderer : ImageRenderer
    {
        public SpriteContainerComponent SpriteSheet { get; set; }

        public int SpriteIndex { get; set; }

        public PropertyReference DirectionReference { get; set; }

        protected Texture2D GetCurrentFrame()
        {
            if (SpriteSheet == null || !SpriteSheet.IsLoaded)
            {
                return null;
            }

            Texture2D curFrame;
            if (DirectionReference != null)
            {
                curFrame = SpriteSheet.GetFrame(SpriteIndex, (float)Owner.GetProperty(DirectionReference));
            }
            else
            {
                curFrame = SpriteSheet.GetFrame(SpriteIndex);
            }

            if (SpriteSheet != null && SpriteSheet.IsLoaded && SpriteSheet.Center.HasValue)
            {
                RegistrationPoint = SpriteSheet.Center.Value;
            }

            return curFrame;
        }

        public override void OnFrame(float deltaTime)
        {
            Texture2D targetTexture = GetCurrentFrame();

            if (ImageData != targetTexture && targetTexture != null)
            {
                ImageData = targetTexture;
            }

            if (targetTexture != null)
            {
                base.OnFrame(deltaTime);
            }
        }
    }
}
